﻿/// <reference path="../Libs/jquery-1.3.2-vsdoc.js"/>
/// <reference path="../Libs/jquery-ui-1.7.2.custom.min.js"/>
/*
COPYRIGHT (C) 2010 EPISERVER AB

THIS FILE IS PART OF SCRUM DASHBOARD.

SCRUM DASHBOARD IS FREE SOFTWARE: YOU CAN REDISTRIBUTE IT AND/OR MODIFY IT UNDER THE TERMS OF 
THE GNU LESSER GENERAL PUBLIC LICENSE VERSION v2.1 AS PUBLISHED BY THE FREE SOFTWARE FOUNDATION.

SCRUM DASHBOARD IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY WARRANTY; WITHOUT
EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU LESSER
GENERAL PUBLIC LICENSE FOR MORE DETAILS.

YOU SHOULD HAVE RECEIVED A COPY OF THE GNU LESSER GENERAL PUBLIC LICENSE ALONG WITH SCRUM DASHBOARD. 
IF NOT, SEE <HTTP://WWW.GNU.ORG/LICENSES/>.
*/

function CascadeProjectToSprint() {

    $("#project").change(function () {

        if (this.value == '') {
            return;
        }
        $("#sprint").empty();
        $("#sprint").append("<option value=''>Loading..</option>");
        var url = "Dashboard/Sprints";

        $.post(url, { projectName: this.value }, 
            function (data) {
                $("#sprint").empty();
                $.each(data, function (index, optionData) {
                    $("#sprint").append("<option value='"
                        + optionData.Id
                        + "'>" + optionData.Title
                        + "</option>");
                });
             }, 
            'json');
    });
}

function CascadeSprintToTeam() {

    $("#sprint").change(function () {

        if (this.value == '') {
            return;
        }
        $("#teamsprint").empty();
        $("#teamsprint").append("<option value=''>Loading..</option>");
        var url = "Dashboard/TeamSprints";
        $.post(url, { projectName: $('#project').val(), sprint: this.value }, function (data) {
            $("#teamsprint").empty();
            $("#teamsprint").append("<option value=''>&lt;all&gt;</option>");
            $.each(data, function (index, optionData) {
                $("#teamsprint").append("<option value='"
                    + optionData.Id
                    + "'>" + optionData.Title
                    + "</option>");
            });
        }, 'json');
    });
}

function openWorkItem(id, project, collection) {
    var wnd = window.open(tfsWebAccessRelative + 'wi.aspx?id=' + id + '&pname=' + encodeURIComponent(project) + '&pcname=' + encodeURIComponent(collection),
			    'WorkItem' + id,
			    'width=800,height=600,toolbar=no,scrollbars=yes,resizable=yes,status=yes');

}

function UnLoadingWorkItem(evt, context) {
    var proxy = new ScrumDashboard.AjaxService();
    proxy.IsLatestVersion(context.id, context.revisionid, onIsLatestVersionSuccess, null, null);
}


//Drag and Drop Support
var dd = {
    moveElement: null, originalElement: null, isDragging: false, isMousePressed: false, lastMouseOverCell: null,
    currentTableRow: null, insertTarget: null, oldState: null, newState: null, assignedTo: null,

    init: function () {
        $('body').mousedown(dd.startDragWorkItem);
        $('body').mousemove(dd.draggingWorkItem);
        $('body').mouseup(dd.stopDragWorkItem);
    },

    //Mouse is pressed on a Work Item
    startDragWorkItem: function (ev) {
        if (ev.target.tagName == 'A' || ev.target.tagName == 'INPUT') {
            return;
        }

        if (dd.isDragging) {
            return;
        }

        var dragBox = $(ev.target).parents('.dragItem');
        if (dragBox.size() != 1)
            return;

        dd.isMousePressed = true;
        dd.moveElement = dragBox.get(0);
        dd.currentTableRow = dragBox.parents("tr").get(0);
        $('body').disableSelection();
    },

    //Work Item is being dragged
    draggingWorkItem: function (ev) {
        if (!dd.isMousePressed || dd.moveElement == null) {
            return;
        }

        if (dd.isMousePressed && !dd.isDragging) {
            dd.isDragging = true;

            dd.originalElement = $(dd.moveElement).clone(true).replaceAll($(dd.moveElement));
            dd.moveElement.style.position = 'absolute';
            $(dd.originalElement).css('opacity', '0');
            $(dd.moveElement).disableSelection();
            $(dd.moveElement).css('opacity', '0.6').appendTo('body');
        }

        dd.moveElement.style.top = ev.pageY + 1 + 'px';
        dd.moveElement.style.left = ev.pageX + 1 + 'px';

        if (dd.lastMouseOverCell){
            dd.lastMouseOverCell.css('background-color', '');
        }

        var targetCell = $(ev.target).parents('.DropTarget').andSelf().filter('td');
        if (targetCell.size() == 0) {
            return;
        }

        if (targetCell.parents('tr').get(0) == dd.currentTableRow) {
            targetCell.css('background-color', '#eeeeee');
            dd.lastMouseOverCell = targetCell;
        }
        else {
            dd.lastMouseOverCell = null;
        }
    },

    //Dragged Work Item is being released somewhere
    stopDragWorkItem: function (ev) {
        if (!dd.isMousePressed) {
            return;
        }
        dd.isMousePressed = false;
        $('body').enableSelection();

        if (!dd.isDragging || dd.moveElement == null) {
            return;
        }

        dd.isDragging = false;

        var target = $(ev.target);
        var targetCellQuery = target.parents('.DropTarget').andSelf().filter('td');
        if (targetCellQuery.size() == 0) {
            dd.reset();
            return;
        }

        var targetCell = targetCellQuery.get(0);
        dd.insertTarget = targetCell;

        //Validate correct drop location
        if (targetCell.parentNode != dd.currentTableRow) {
            dd.reset();
            return;
        }

        dd.newState = targetCellQuery.attr('dropState');
        dd.oldState = $(dd.moveElement).attr('taskState');

        if (dd.newState != null && dd.oldState!=dd.newState) {
            $.post('Dashboard/MoveToState', { workItemID: $(dd.moveElement).attr('taskId'), state: dd.newState }, dd.onMoveToStateSuccess,'json');
        }
        else {
            dd.reset();
        }
    },

    //Reset dragged Work Item
    reset: function () {
        if (dd.moveElement != null) {
            $(dd.moveElement).replaceAll($(dd.originalElement)).css({ position: 'relative', top: 0, left: 0, opacity: '1' });
            $(dd.originalElement).remove();
            dd.originalElement = null;
            dd.moveElement = null;
        }

        if (dd.lastMouseOverCell != null) {
            dd.lastMouseOverCell.css('background-color', '');
            dd.lastMouseOverCell = null;
        }
    },

    //Close the dialog (called from AssignTo.ascx)
    closeAssignedToDialog: function () {
        hideAssignToDialog($(dd.moveElement).attr('taskId'));
    },

    //Callback from webservice when move to state succeeded
    onMoveToStateSuccess: function (result) {
        
        if(!result)
        {
            dd.reset();
            alert("State transition from " + dd.oldState + " to " + dd.newState + " is not allowed");
            return;
        }
        
        var j = $(dd.moveElement);
        j.attr('taskState', dd.newState);
        j.css({ opacity: '1', position: 'relative', left: 0, top: 0 });
        j.appendTo($(dd.insertTarget));

        if (!j.hasClass('TaskUnplanned')) {
            j.removeClass('Task' + dd.oldState.replace(/\s/g, ''));
            j.addClass('Task' + dd.newState.replace(/\s/g, ''));
        }

        j.slideDown();

        $(dd.originalElement).remove();

//        if (j.attr('taskAssignedTo') == '') {
//            showAssignToDialog(j.attr('taskId'), true);
//        }

        dd.moveElement = null;
        dd.reset();
    },

    //Called to assign the currently dropped work item to a specific user (called from AssignTo.ascx)
    assignToUser: function (name) {
        var workitemID = $(dd.moveElement).attr('taskId')
        var state = $(dd.moveElement).attr('taskState');
        var assignedTo = name;
        dd.assignedTo = name;

        var proxy = new ScrumDashboard.AjaxService();
        proxy.AssignTo(workitemID, state, assignedTo, dd.assignToSuccess, dd.assignFailed, null);

        hideAssignToDialog();
    },

    //Callback from webservice when assign to user succeeded
    assignToSuccess: function (result) {
        var changeAssign = $('#assignedTO' + $(dd.moveElement).attr('taskId').toString());
        var name = dd.assignedTo;

        $(dd.moveElement).attr('taskAssignedTo', name);
        changeAssign.text(result.Initials);

        dd.assignedTo = null;
    },

    //Callback from webservice when assign to user failed
    assignFailed: function (error) {
        alert(error.get_message());
    }
}

var workRemaining = {
    originalHtml: '', workItemId: null, isActive: false, target: null,

    //Click on Work Remaining to change the time
    edit: function (target, workItemId) {

        if (workRemaining.isActive) {
            return;
        }
        
        target = target.find(".TaskWorkRemaining");

        var input = $('<input type="text" style="text-align:right;width:20px;" value="' + target.text() + '" />');

        workRemaining.target = target;
        workRemaining.workItemId = workItemId;
        workRemaining.isActive = true;
        workRemaining.originalHtml = target.html();

        target.keypress(workRemaining.keypress);
        $(document).mousedown(workRemaining.click);

        try {
            target.empty();
            target.append(input);
            input.focus();
        } catch (err) { }
    },

    //Handles keypress when user is changing Work Remaining
    keypress: function (ev) {
        var target = $(ev.target);
        var pattern = new RegExp("^[0-9]{1,3}$");
        var keynum = ev.which;

        //If 'Enter' was pressed we save
        if (keynum == $.ui.keyCode.ENTER) {
            if (!pattern.test(target.val())) {
                alert('Only number between 0-999!');
            }
            else {
                var time = parseFloat(target.val());
                if (target.parent() != null) {
                    target.parent().html(time.toString());
                }

                $.post('Dashboard/UpdateWorkRemaining', { workItemID: workRemaining.workItemId, workRemaining: time });

                workRemaining.quit();
            }
            return false;
        }
        
        //If 'Escape' was pressed we cancel
        if (keynum == $.ui.keyCode.ESCAPE) {
            $(workRemaining.target).html(workRemaining.originalHtml);
            workRemaining.quit();
            return false;
        }
    },

    //Handles cancellation of change time
    quit: function () {
        $(workRemaining.target).unbind('keypress', workRemaining.keypress);
        $(document).unbind('mousedown', workRemaining.click);
        workRemaining.isActive = false;
        workRemaining.target = null;
    },

    //Handles click outside input box
    click: function (ev) {
        if (ev.target == workRemaining.target || ev.target == workRemaining.target.firstChild) {
            return false;
        }

        $(workRemaining.target).html(workRemaining.originalHtml);
        workRemaining.quit();
    }
}

var AjaxLoader = '&nbsp;<img style="display: none" class="ajaxLoader" src="Content/Shared/ajax-loader.gif" />';
$(window).ajaxSend(function () {
    $(".ajaxLoader").show();
});

$(window).ajaxSuccess(function () {
    $(".ajaxLoader").hide();
});

$(window).ajaxError(function (event, request, settings) {
    $(".ajaxLoader").hide();
    dd.reset();
    var err = $('<div></div>');
    err.html(request.responseText);
    err.appendTo('body');
    err.dialog();
});

function CreateNewTask(form) {
    form.validate();

    if (!form.valid()) {
        return;
    }

    $.post(
        form.attr('action'),
        form.serialize(),
        function (data) {
            var $result = $(data);

            if ($result.find("form.NewItem").length > 0) {
                // validation error
                $(form).closest(".ui-dialog-content").html($result);
            } else {
                var state = form.find("input[name='State']").val();
                var backlogId = form.find("input[name='ProductBacklogId']").val();
                $("td[pbId='" + backlogId + "']")
                    .filter("td[dropState='" + state + "']")
                    .append(data)
                    .trigger("taskschanged");
                form.find('input:text,textarea').val('').slice(0, 1).focus();
            }
        }
    );
    }

function NewProductBacklogItem(form) {
    form.validate();

    if (!form.valid()) {
        return;
    }

    $.post(
    form.attr('action'),
    form.serialize(),
    function (data) {
        form.dialog('close');
        window.location.reload();
    }
    );
}

function ImportTask(form) {

    $.post(
        form.attr('action'),
        form.serialize(),
        function (data) {
            var $result = $(data);
            var state = form.find("input[name='State']").val();
            var backlogId = form.find("input[name='ProductBacklogId']").val();
            $("td[pbId='" + backlogId + "']")
                .filter("td[dropState='" + $result.find("div:first").attr("taskState") + "']")
                .append($result.html())
                .trigger("taskschanged");
            form.dialog('close');
        }
    );
    }

function AddProductBacklogItem(form) {
    form.validate();

    if (!form.valid()) {
        return;
    }

    $.post(
    form.attr('action'),
    form.serialize(),
    function (data) {
        form.dialog('close');
        window.location.reload();
    }
    );
}
    
    

function ShowTaskDialog(productBacklogId, type) {
    
        var dialog = $('form.New' + type);
        dialog.find('#ProductBacklogId').val(productBacklogId);
        dialog.dialog("open");
        
    return false;
};

function ShowTaskImportDialog(productBacklogId, type) {

    var dialog = $('form.ImportTaskDialog');
    dialog.find('#ProductBacklogId').val(productBacklogId);
    dialog.find('#BacklogType').val(type);
    dialog.dialog("open");

    $('#importList').setTemplate($("#ImportTemplate").html());
    $('#importList').html('');
    $('#importQuery').val('');

    return false;
};

function ShowNewProductBacklogItemDialog() {

    var dialog = $('form.NewProductBacklogItemDialog');
    dialog.find('#sprint').val($('#sprint').val());
    dialog.find('#teamsprint').val($('#teamsprint').val());
    dialog.dialog("open");

    return false;
};

function ShowAddProductBacklogItemDialog() {

    var dialog = $('form.AddProductBacklogItemDialog');
    dialog.find('#sprint').val($('#sprint').val());
    dialog.find('#teamsprint').val($('#teamsprint').val());
    dialog.dialog("open");

    $('#addProductBacklogItemList').setTemplate($("#AddProductBacklogItemTemplate").html());
    $('#addProductBacklogItemList').html('');
    $('#addProductBacklogItemQuery').val('');

    $("#addProductBacklogItemQuery").empty();
    $("#addProductBacklogItemQuery").append("<option value=''>Loading..</option>");
    var url = "Dashboard/Queries/?projectName=" + $('#project').val();
    $.post(url, null, function (data) {
        $("#addProductBacklogItemQuery").empty();
        $("#addProductBacklogItemQuery").append("<option value=''>&lt;all&gt;</option>");
        $.each(data, function (index, optionData) {
            $("#addProductBacklogItemQuery").append("<option value='"
                + optionData.Id
                + "'>" + optionData.Title
                + "</option>");
        });
        }, "json");

    return false;
};

function FilterBasedOnTabs() {
    function HandleTabCheckChanged(){
        var isChecked = $(this).attr("checked");
        var rowSelector = "." + this.name;

        // make tab-like appearance
        $(this).closest("label").siblings().andSelf().each(function(){
            if($(this).find("input").attr("checked")){
                $(this).addClass("Checked").removeClass("Unchecked");
            }else{
                $(this).addClass("Unchecked").removeClass("Checked");
            }
        });

        // Show/Hide associated rows on the workspace
        $(".Toggleable")
            .filter(rowSelector)
            .addClass(isChecked ? "visible" : "invisible").removeClass(isChecked ? "invisible" : "visible");
    }

    // Apply current state and listen for changes
    $("#tools input").click(HandleTabCheckChanged).keyup(HandleTabCheckChanged).each(HandleTabCheckChanged);


    function HandleTaskMode(){
        $("#tools .TaskMode input").each(function(){
            var className = this.value;
            var isChecked = this.checked;
            if(isChecked)
                $(".Workspace").addClass(className);
            else
                $(".Workspace").removeClass(className);
        });
    }
    $("#tools .TaskMode input").click(HandleTaskMode).keyup(HandleTaskMode).each(HandleTaskMode);
    

    function HandlyMyTasks(){
        if(this.checked){
            $(".Task[taskAssignedTo!='" + currentUserInitials + "']").hide();
        }
        else{
            $(".Task[taskAssignedTo!='" + currentUserInitials + "']").show();
        }   
    }
    $("#tools .OnlyMyTasks input[type='checkbox']").click(HandlyMyTasks).keyup(HandlyMyTasks).each(HandlyMyTasks);


    function HandleExpandAll() {
        if (this.checked) {
            $(".ProductBacklog .Togglers .ShowWorkItems").click();
        }
        else {
            $(".Backlog-NotStarted .Togglers .HideWorkItems").click();
            $(".Backlog-Done .Togglers .HideWorkItems").click();
            $(".Backlog-Deleted .Togglers .HideWorkItems").click();
        }
   }

    $(".Tabs .ExpandAll input[type='checkbox']").click(HandleExpandAll);

    $('#overview-placeholder').hide();
    $(".Tabs .Overview input[type='checkbox']").click(HandleOverview);

}

function EnableProductTasksToggling()
{
    $(".Togglers a").click(function (e) {
        e.preventDefault();
        $(this).hide().closest(".ProductBacklog").addClass(this.className);
        $(this).siblings("a").show().each(function(){
            $(this).closest(".ProductBacklog").removeClass(this.className);
        });
    });

    $(".Backlog-Done .Togglers .HideWorkItems").click();
    $(".Backlog-NotStarted .Togglers .HideWorkItems").click();
    $(".Backlog-Deleted .Togglers .HideWorkItems").click();
    
}

function EnableAddTaskButtons()
{
    $(".TaskAdd").live("click", function(e){
        e.preventDefault();

        var type = $(this).attr("data-type");
        var backlogId = $(this).closest(".ProductBacklog").attr("data-productbacklogid");
        ShowTaskDialog(backlogId, type);
    });

    $(".TaskImport").live("click", function (e) {
        e.preventDefault();

        var type = $(this).attr("data-type");
        var backlogId = $(this).closest(".ProductBacklog").attr("data-productbacklogid");
        ShowTaskImportDialog(backlogId, type);
    });

    $(".NewProductBacklogItem").live("click", function (e) {
        e.preventDefault();
        ShowNewProductBacklogItemDialog();
    });

    $(".AddProductBacklogItem").live("click", function (e) {
        e.preventDefault();
        ShowAddProductBacklogItemDialog();
    });
    
}

function getParameterByName( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
      return decodeURIComponent(results[1]).replace(/\+/g, ' ');
}


function HandleOverview()
{
    var placeholder = $('#overview-placeholder');
    if(placeholder.is(":visible"))
    {
        placeholder.hide();
    }
    else{
        placeholder.html("<div style='padding-left: 20px'>" + AjaxLoader + "</div>");
        placeholder.show();
        placeholder.load("Dashboard/Overview", { project: getParameterByName("project"), sprint: getParameterByName("sprint"), teamsprint: getParameterByName("teamsprint")  }, function(e){
            $("input:first", this).focus();
        });
    }

}

function InitUIElements() {
    $('#dashboardTabs').tabs({ cache: true, select: function(event, ui) {window.location.hash = $(ui.tab).attr("href").split("#")[1];}});
    $('#loadbutton').hover(
    	function(){ 
    		$(this).addClass("ui-state-hover"); 
    	},
    	function(){ 
    		$(this).removeClass("ui-state-hover"); 
    	}
    );
    CascadeSprintToTeam();
    CascadeProjectToSprint();
    FilterBasedOnTabs();
    EnableAddTaskButtons();
    EnableProductTasksToggling();


    var dialog1 = $("form.NewSprintBacklogTask");
    dialog1.dialog({
                            title: 'New Sprint Backlog Task' + AjaxLoader,
                            buttons: { "Save": function () { CreateNewTask(dialog1); }  },
                            minWidth: 500,
                            minHeight: 400,
                            autoOpen: false
                        });
    var dialog2 = $("form.NewAcceptanceTest");
    dialog2.dialog({
                            title: 'New Acceptance Test' + AjaxLoader,
                            buttons: { "Save": function () { CreateNewTask(dialog2); }  },
                            minWidth: 500,
                            minHeight: 400,
                            autoOpen: false
                        });
    var dialog3 = $("form.NewImpediment");
    dialog3.dialog({
                            title: 'New Impediment' + AjaxLoader,
                            buttons: { "Save": function () { CreateNewTask(dialog3); }  },
                            minWidth: 500,
                            minHeight: 400,
                            autoOpen: false
                        });

    var dialog4 = $("form.ImportTaskDialog");
    dialog4.dialog({
        title: 'Import..' + AjaxLoader,
        buttons: { "Import": function () { ImportTask(dialog4); } },
        width: 800,
        height: 500,
        minWidth: 500,
        minHeight: 500,
        autoOpen: false
    });

    var dialog5 = $("form.NewProductBacklogItemDialog");
    dialog5.dialog({
        title: 'New Product Backlog Item' + AjaxLoader,
        buttons: { "Save": function () { NewProductBacklogItem(dialog5); } },
        width: 500,
        height: 500,
        minWidth: 500,
        minHeight: 500,
        autoOpen: false
    });

    var dialog6 = $("form.AddProductBacklogItemDialog");
    dialog6.dialog({
        title: 'Add Product Backlog Item' + AjaxLoader,
        buttons: { "Add": function () { AddProductBacklogItem(dialog6); } },
        width: 800,
        height: 500,
        minWidth: 500,
        minHeight: 500,
        autoOpen: false
    });

    $("#importProject").change(function () {

        if (this.value == '') {
            return;
        }
        $("#importQuery").empty();
        $("#importQuery").append("<option value=''>Loading..</option>");
        var url = "Dashboard/Queries/?projectName=" + $('#importProject').val();
        $.post(url, null, function (data) {
            $("#importQuery").empty();
            $("#importQuery").append("<option value=''>&lt;all&gt;</option>");
            $.each(data, function (index, optionData) {
                $("#importQuery").append("<option value='"
                    + optionData.Id
                    + "'>" + optionData.Title
                    + "</option>");
            });
        }, "json");
    });

    $("#importQuery").change(function () {

        if (this.value == '') {
            return;
        }

        var url = "Dashboard/RunQuery/?projectName=" + $('#importProject').val() + '&queryId=' + this.value;
        $.post(url, null, function (data) {
            
            $('#importList').processTemplate(data);
        }, "json");
    });

    $("#addProductBacklogItemQuery").change(function () {

        if (this.value == '') {
            return;
        }

        var url = "Dashboard/RunQuery/?projectName=" + $('#project').val() + '&queryId=' + this.value;
        $.post(url, null, function (data) {

            $('#addProductBacklogItemList').processTemplate(data);
        }, "json");
    });


    var allFormOptions = window.mvcClientValidationMetadata;
    if (allFormOptions) {
        while (allFormOptions.length > 0) {
            var thisFormOptions = allFormOptions.pop();
            __MVC_EnableClientValidation(thisFormOptions);
        }
    }
}

$(InitUIElements);
$(dd.init);
